/********************************************************************************
 * Project Name		[JavaEE_JDBC]
 * File Name     	[ConnectionUtils.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package utils.jdbc;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Properties;

import org.junit.Test;

/**
 * 使用DriverManager获取数据库连接的几种方式
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class ConnectionUtils {

	/**
	 * 使用具体的实现类来获取Connection<br/>
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection(Driver driver, Properties databaseProperties, String url) throws Exception {
		return driver.connect(url, databaseProperties);
	}

	public static Connection getConnection(String driverClassName, Properties databaseProperties, String url)
			throws Exception {
		Driver driver = (Driver) Class.forName(driverClassName).newInstance();
		return driver.connect(url, databaseProperties);
	}

	/**
	 * 使用DriverManager来获取JDBC Connection
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection(String driverClass, String username, String password, String url)
			throws Exception {
		Class.forName(driverClass);
		return DriverManager.getConnection(url, username, password);
	}

	@Test
	public void testGetConnections() throws Exception {
		String username = "root";
		String password = "123456";
		String driverClass = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/jdbc";

		Properties databaseProperties = new Properties();
		databaseProperties.put("user", username);
		databaseProperties.put("password", password);

		System.out.println(getConnection(new com.mysql.jdbc.Driver(), databaseProperties, url));
		System.out.println(getConnection("com.mysql.jdbc.Driver", databaseProperties, url));
		System.out.println(getConnection(driverClass, username, password, url));
	}
}
